package com.xiaotu.controller;

import com.xiaotu.model.EnterpriseFileModel;
import com.xiaotu.model.MyFile;
import com.xiaotu.model.ParamModel;
import com.xiaotu.service.FileService;
import com.xiaotu.utils.AttachmentType;
import com.xiaotu.utils.FileUtils;
import com.xiaotu.utils.PropertiesUitls;
import com.xiaotu.utils.UUIDUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 上传下载文件
 * @author wangyanlong
 * @date 2021年1月29日 上午11:59:14
 *
 */
@RestController
@CrossOrigin
@RequestMapping("/fileManager")
public class FileController {

    @Autowired
    private FileService fileService;

    private static Properties properties;

    private static SimpleDateFormat sdf;

    static {
        try {
            properties = PropertiesUitls.fetchProperties("/application.properties");
        } catch (IOException e) {
            e.printStackTrace();
        }
        sdf = new SimpleDateFormat("yyyyMMdd");
    }

    /**
     * 根据扫描件id获取企业文件记录
     * @param param
     * @return
     */
    @PostMapping("/queryFileDetailInfo")
    public Object queryFileDetailInfo(ParamModel param) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(param.getEnterpriseId())) {
            throw new java.lang.IllegalArgumentException("请提供企业id");
        }
        if (StringUtils.isEmpty(param.getMenuId())) {
            throw new java.lang.IllegalArgumentException("请提供菜单id");
        }
        if (StringUtils.isEmpty(param.getApplyId())) {
            throw new java.lang.IllegalArgumentException("请提供申请id");
        }
        if (StringUtils.isEmpty(param.getFileTabId())) {
            throw new java.lang.IllegalArgumentException("请提供附件tab项id");
        }
        //获取列表记录
        List<EnterpriseFileModel> dataList = fileService.queryFileDetailInfo(param);
        resultMap.put("data", dataList);
        return resultMap;
    }

    /**
     * 上传文件
     * @param param
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping("/uploadFile")
    public Object uploadFile(ParamModel param, MultipartFile file) throws Exception {
        //public Object uploadFile(HttpServletRequest request, ParamModel param)throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //MyFile file = new MyFile(new File("C:/Users/Administrator/Desktop/文化产业综合服务平台-0301.rar"));
        String[] str =new String[]{"C:/Users/Administrator/Desktop/新版爬虫任务整理.xlsx",
                "C:/Users/Administrator/Desktop/RabbitMQ222.docx","C:/Users/Administrator/Desktop/环境文档.txt",
                "C:/Users/Administrator/Desktop/tu.png"};
        /*for (String fileStr:str) {
            MyFile file = new MyFile(new File(fileStr));
            if (file == null) {
                throw new java.lang.IllegalArgumentException("请提供需要上传的文件");
            }*/
            if (StringUtils.isEmpty(param.getEnterpriseId())) {
                throw new java.lang.IllegalArgumentException("请提供企业id");
            }
            if (StringUtils.isEmpty(param.getMenuId())) {
                throw new java.lang.IllegalArgumentException("请提供菜单id");
            }
            if (StringUtils.isEmpty(param.getApplyId())) {
                throw new java.lang.IllegalArgumentException("请提供申请id");
            }
            if (StringUtils.isEmpty(param.getFileTabId())) {
                throw new java.lang.IllegalArgumentException("请提供附件tab项id");
            }
            String baseStorePath = properties.getProperty("fileupload.path");
            String storePath = baseStorePath+param.getEnterpriseId()+"/"+param.getMenuId()+"/";

            //上传之前，先删除之前上传过的附件
            fileService.deleteFileInfo(baseStorePath,param.getFileId());


            //把附件上传到服务器(高清原版)
            Map<String, String> fileMap = FileUtils.uploadFile(file, false, storePath);
            String fileStoreName = fileMap.get("fileStoreName");
            String fileRealName = fileMap.get("fileRealName");

            //文件存储真实路径
            String realPath = fileMap.get("storePath") + fileStoreName;
            //数据库存储路径
            String dbStorePath = realPath.replace(baseStorePath, "");

            int lastCommaIndex = fileStoreName.length();
            if (fileStoreName.lastIndexOf(".") != -1) {
                lastCommaIndex = fileStoreName.lastIndexOf(".");
            }
            String suffix = "";//文件后缀
            if (lastCommaIndex != fileStoreName.length()) {
                suffix = fileStoreName.substring(lastCommaIndex);
            }


            String type = AttachmentType.Others.getValue();
            //判断是否是图片文件
            if (FileUtils.isPicture(realPath)) {
                type = AttachmentType.Picture.getValue();
            }
            if (suffix.equals(".doc") || suffix.equals(".docx")) {
                type = AttachmentType.Word.getValue();
            }
            if (suffix.equals(".mp3") || suffix.equals(".amr") || suffix.equals(".wav")) {
                type = AttachmentType.Audio.getValue();
            }
            if (suffix.equals(".mp4") || suffix.equals(".AVI") || suffix.equals(".wma")
                    || suffix.equals(".rmvb") || suffix.equals(".rm") || suffix.equals(".flash")
                    || suffix.equals(".3GP")) {
                type = AttachmentType.Video.getValue();
            }

            //音频文件获取文件的声音长度
            long length = 0;
            if (type == AttachmentType.Audio.getValue()) {
                if (suffix.equals(".avi") || suffix.equals(".mpeg")
                        || suffix.equals(".rmvb") || suffix.equals(".mp4")) {
                    Clip clip = AudioSystem.getClip();
                    AudioInputStream ais = AudioSystem.getAudioInputStream(new File(realPath));
                    clip.open(ais);
                    length = clip.getMicrosecondLength() / 1000000;
                }
            }

            if (type == AttachmentType.Video.getValue()) {
                length = FileUtils.ReadVideoTime(new File(realPath));
            }

            long size = FileUtils.getFileSize(realPath);

            EnterpriseFileModel fileModel = new EnterpriseFileModel(fileRealName,type,suffix,size,length,dbStorePath,
                    param.getEnterpriseId(),param.getMenuId(),param.getApplyId(), param.getFileTabId(),param.getFileTitleId());
            fileService.addFileInfo(fileModel);
            //resultMap.put("data",fileModel);
       // }


        return resultMap;
    }


    /**
     * 企业文件同步到房租通文件
     * @param param
     * @return
     */
    @ResponseBody
    @RequestMapping("/copyFile")
    public Object copyFile(ParamModel param) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(param.getEnterpriseId())) {
            throw new java.lang.IllegalArgumentException("请提供企业id");
        }
        if (StringUtils.isEmpty(param.getMenuId())) {
            throw new java.lang.IllegalArgumentException("请提供菜单id");
        }
        if (StringUtils.isEmpty(param.getApplyId())) {
            throw new java.lang.IllegalArgumentException("请提供申请id");
        }
        if (StringUtils.isEmpty(param.getFileTabId())) {
            throw new java.lang.IllegalArgumentException("请提供附件tab项id");
        }
        if (StringUtils.isEmpty(param.getFileTitleId())) {
            throw new java.lang.IllegalArgumentException("请提供附件标题名id");
        }
        Map<String, Object> enterpriseModel = fileService.queryEnterpriseInfo(param.getEnterpriseId());
        if(null == enterpriseModel){
            return false;
            //throw new IllegalArgumentException("没有需要同步的企业附件");
        }else{
            if(null ==enterpriseModel.get("business_license_path")){
                //throw new IllegalArgumentException("没有需要同步的企业附件");
                return false;
            }
        }

        String baseStorePath = properties.getProperty("fileupload.path");
        String storePath = baseStorePath+param.getEnterpriseId()+"/"+param.getMenuId()+"/";

        String fileRealName = enterpriseModel.get("business_license_path")+"";
        String suffix = "";
        if (fileRealName.lastIndexOf(".") != -1) {
            suffix = fileRealName.substring(fileRealName.lastIndexOf("."));
        }
        // 生成文件存储名称
        String fileStoreName = UUIDUtil.getId() + suffix;

        //上传文件到服务器
        File folder = new File(storePath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        File inFile = new File(baseStorePath + fileRealName);
        File onFile = new File(storePath + fileStoreName);
        FileCopyUtils.copy(inFile,onFile);

        //文件存储真实路径
        String realPath = storePath + fileStoreName;
        //数据库存储路径
        String dbStorePath = realPath.replace(baseStorePath, "");

        String type = AttachmentType.Others.getValue();
        //判断是否是图片文件
        if (FileUtils.isPicture(realPath)) {
            type = AttachmentType.Picture.getValue();
        }

        long size = FileUtils.getFileSize(realPath);

        String fileName = enterpriseModel.get("business_license_name")+"";
        EnterpriseFileModel fileModel = new EnterpriseFileModel(fileName,type,suffix,size,0,dbStorePath,
                param.getEnterpriseId(),param.getMenuId(),param.getApplyId(), param.getFileTabId(),param.getFileTitleId());
        fileService.addFileInfo(fileModel);

        return resultMap;
    }


    /**
     * 房租通文件拷贝到企业文件
     * @param param
     * @return
     */
    @ResponseBody
    @RequestMapping("/autosynCopyFile")
    public Object autosynCopyFile(ParamModel param) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(param.getFilePath())) {
            throw new java.lang.IllegalArgumentException("请提供文件地址");
        }
        if (StringUtils.isEmpty(param.getFileName())) {
            throw new java.lang.IllegalArgumentException("请提供文件名称");
        }
        if (StringUtils.isEmpty(param.getEnterpriseId())) {
            throw new java.lang.IllegalArgumentException("请提供企业id");
        }
        if (StringUtils.isEmpty(param.getMenuId())) {
            throw new java.lang.IllegalArgumentException("请提供菜单id");
        }
        Map<String, Object> enterpriseModel = fileService.queryEnterpriseInfo(param.getEnterpriseId());
        if(null == enterpriseModel){
            return false;
            //throw new IllegalArgumentException("没有需要同步的企业附件");
        }else{
            if(null ==enterpriseModel.get("business_license_path")){
                return false;
                //throw new IllegalArgumentException("没有需要同步的企业附件");
            }
        }

        String baseStorePath = properties.getProperty("fileupload.path");
        String storePath = baseStorePath+param.getEnterpriseId()+"/"+param.getMenuId()+"/";

        String fileRealName = param.getFilePath();
        String suffix = "";
        if (fileRealName.lastIndexOf(".") != -1) {
            suffix = fileRealName.substring(fileRealName.lastIndexOf("."));
        }
        // 生成文件存储名称
        String fileStoreName = UUIDUtil.getId() + suffix;

        //上传文件到服务器
        File folder = new File(storePath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        File inFile = new File(baseStorePath + param.getFilePath());
        File onFile = new File(storePath + fileStoreName);
        FileCopyUtils.copy(inFile,onFile);

        //先把原有的企业附件照片删除，
        String business_license_path = enterpriseModel.get("business_license_path")+"";
        FileUtils.deleteFile(business_license_path);

        //更新企业基本信息营业执照
        String realPath = storePath + fileStoreName;
        //数据库存储路径
        String businessLicensePath = realPath.replace(baseStorePath, "");
        String fileName = param.getFileName();
        fileService.updateEnterpriseInfo(businessLicensePath,fileName,param.getEnterpriseId());

        return resultMap;
    }

    /**
     * 删除文件
     * @param request
     * @param fileId  文件ID
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteFile")
    public Object deleteFile(HttpServletRequest request, Integer fileId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (null ==fileId) {
            throw new IllegalArgumentException("请选择需要删除的文件");
        }
        String baseDownLoadPath = properties.getProperty("fileupload.path");
        fileService.deleteFileInfo(baseDownLoadPath,fileId);
        return null;
    }

    /**
     * 批量删除文件
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteBatchFile")
    public Object deleteBatchFile(HttpServletRequest request,ParamModel param) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(param.getEnterpriseId())) {
            throw new java.lang.IllegalArgumentException("请提供企业id");
        }
        if (StringUtils.isEmpty(param.getMenuId())) {
            throw new java.lang.IllegalArgumentException("请提供菜单id");
        }
        if (StringUtils.isEmpty(param.getApplyId())) {
            throw new java.lang.IllegalArgumentException("请提供申请id");
        }
        String baseDownLoadPath = properties.getProperty("fileupload.path");
        List<EnterpriseFileModel> dataList = fileService.queryFileDetailInfo(param);
        for (EnterpriseFileModel enterpriseFileModel : dataList) {
            if(null !=enterpriseFileModel && null !=enterpriseFileModel.getId()){
                fileService.deleteFileInfo(baseDownLoadPath,enterpriseFileModel.getId());
            }
        }
            return null;
    }


    /**
     * 根据地址下载文件
     * @param response
     * @param fileId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/downloadFile")
    public void downloadFile(HttpServletResponse response, Integer fileId) throws Exception{
        InputStream is = null;
        OutputStream os = null;
        try {
            if (null ==fileId) {
                throw new IllegalArgumentException("文件ID不能为空");
            }

            String baseStorePath = properties.getProperty("fileupload.path");
            //根据id获取文件信息
            EnterpriseFileModel enterpriseFileModel = fileService.queryFileInfo(fileId);
            String address = baseStorePath + enterpriseFileModel.getStorePath();
            String fileName = enterpriseFileModel.getFileName();

            File file = new File(address);
            if (!file.exists()) {
                throw new IllegalArgumentException("找不到文件");
            }
            String name = java.net.URLEncoder.encode(fileName, "UTF-8");

            response.setHeader("Content-Disposition", "attachment;fileName=" + name);
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");

            is = new FileInputStream(address);
            os = response.getOutputStream();
            byte[] b = new byte[1024];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }

        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }

}
